package com.ty.common.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.Data;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * @author 天宇宇宇宇宇
 * @Data 2020/12/2 14:03
 */
@Data
@Configuration
@PropertySource(value = "classpath:sms/sms.properties")
public class SmsUtil {

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.sms.signName}")
    private String signName;
    @Value("${aliyun.sms.templates.authentication.templateCode}")
    private String templateCode;

    public String sendSms(String phoneNumber, String code) {
        //配置文件类 ,读取配置文件
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);


        //配置请求参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");   //查询参数  , 服务器所在地

        //设置 手机号
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        //设置标签名称
        request.putQueryParameter("SignName", signName);
        //模板 code
        request.putQueryParameter("TemplateCode", templateCode);
        //模板是一个json样式
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");

        try {
            CommonResponse response = client.getCommonResponse(request);    //通过客户端拿到 阿里服务器 响应的 短信内容
            return response.getData();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取4位随机数
     * @return
     */
    public static String getFourRandom(){
        Random random = new Random();
        String fourRandom = random.nextInt(10000) + "";
        int randLength = fourRandom.length();
        if(randLength<4){
            for(int i=1; i<=4-randLength; i++) {
                fourRandom = "0" + fourRandom ;
            }
        }
        return fourRandom;
    }
}
